package com.rfqx.controller;

import static com.rfqx.util.StringHelper.nullToEmpty;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rfqx.entity.Login;
import com.rfqx.service.UserService;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/login")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginController() {
        super();
    }

	protected void doPost(HttpServletRequest request
						, HttpServletResponse response) throws ServletException, IOException {
		
		
		UserService service = new UserService();
		
		Login login = new Login();
		login.setUserName( nullToEmpty ( request.getParameter("username")) ); 
		login.setPassword( nullToEmpty ( request.getParameter("password") ) );
		
		HttpSession session = request.getSession();
		
		if (session.getAttribute("user") != null) {
			response.sendRedirect("welcome.jsp");			
			return;
		}
		
		if ( service.isValidLogin(login) ) {
			
			session.setAttribute("user", login );
			
			response.sendRedirect("welcome.jsp");
			
			return;
		
		} else {

			request.setAttribute("message"
								, "Usuario nao Encontrado :_(");
			
			RequestDispatcher dispatcher = 
						request.getRequestDispatcher("index.jsp");
			
			dispatcher.forward(request, response);
			
		}
		
		
	
		
		
	}

}
